﻿using AI.Common;
using Spectre.Console;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Text.Encodings.Web; // added for JSON encoder
using System.Text.Json; // added for serializer options

namespace AI.Demo.RoomsAnalyzeTool
{
    internal class Program
    {
        // C# 7.1+ 支持；项目已是 .NET 8 可用
        private static async Task Main(string[] args)
        {
            bool evalMode = args.Length > 0 && string.Equals(args[0], "eval", StringComparison.OrdinalIgnoreCase);

            AnsiConsole.Write(new FigletText("Analyze Data").Centered().Color(Color.FromInt32(new Random().Next(1, 255))));
            var cts = new CancellationTokenSource();
            Console.CancelKeyPress += (_, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("收到取消信号，正在退出...");
            };

            try
            {
                Console.WriteLine("[1] 开始加载 Google Sheet 数据...");
                var analyzeHistoryDataService = new AnalyzeHistoryDataService();
                await RunWithTimeout(
                    analyzeHistoryDataService.LoadGoogleSheetData(),
                    TimeSpan.FromMinutes(2),
                    "加载表数据");
                Console.WriteLine("[1] 数据加载完成，记录数: " + analyzeHistoryDataService.ProdCPRRecords.Count);

                Console.WriteLine("[2] 初始化 ChatHelper 连接...");
                var chat = await ChatHelper.CreateAsync(); // 新的异步工厂
                Console.WriteLine("[2] ChatHelper 连接测试完成。");

                Console.WriteLine("[3] 初始化 AI 相似度索引...");
                await RunWithTimeout(
                    analyzeHistoryDataService.InitializeSimilarityAsync(chat, cts.Token),
                    TimeSpan.FromMinutes(2),
                    "AI 相似度索引初始化");
                Console.WriteLine("[3] AI 相似度索引初始化完成。");

                if (evalMode)
                {
                    Console.WriteLine("[E] 执行自动评估 (本地相似度) ...");
                    var evalJson = await analyzeHistoryDataService.EvaluateSimilarityAsync(sampleSize: 60);
                    Console.WriteLine("[E] 评估结果(JSON)：");
                    Console.WriteLine(evalJson);
                    Console.WriteLine("[E] 评估完成，程序退出。");
                    return;
                }

                Console.WriteLine();
                Console.WriteLine("[4] 进入交互查询阶段。");
                while (true)
                {
                    Console.WriteLine("*************************************************************");
                    Console.WriteLine("请输入新的 Crash Stack，多行输入，结束请输入单独一行 'END':");

                    string? line;
                    var sb = new System.Text.StringBuilder();
                    while (!string.Equals(line = Console.ReadLine(), "END", StringComparison.OrdinalIgnoreCase))
                    {
                        if (line is null)
                        {
                            Console.WriteLine("标准输入已结束。");
                            break;
                        }
                        sb.AppendLine(line);
                    }

                    Console.Write("设备信息: ");
                    string device = Console.ReadLine() ?? "";

                    Console.WriteLine("[5] 正在向 AI 查询相似案例...");
                    var result = await analyzeHistoryDataService.QuerySimilarAsync(sb.ToString(), device, topN: 3);
                    Console.WriteLine("AI 返回结果(JSON)：");
                    // Use relaxed encoder to avoid Chinese being escaped (\uXXXX)
                    var printOptions = new JsonSerializerOptions
                    {
                        WriteIndented = true,
                        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    };
                    Console.WriteLine(JsonSerializer.Serialize(result, printOptions));
                    Console.WriteLine("*************************************************************");
                }
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("操作已取消。");
            }
            catch (Exception ex)
            {
                Console.WriteLine("程序执行出错：" + ex);
            }

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }

        private static async Task RunWithTimeout(Task task, TimeSpan timeout, string name)
        {
            var finished = await Task.WhenAny(task, Task.Delay(timeout));
            if (finished != task)
            {
                throw new TimeoutException($"{name} 超过超时时间 {timeout}。");
            }
            await task; // 传播异常
        }
    }
}